package com.crois.barrier.web.loadbalance.rule;


import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.crois.barrier.common.exception.BarrierException;
import com.crois.barrier.common.exception.BarrierExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.server.ServerWebExchange;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Hou Ze Yu
 * @description 根据serviceName 从 ncaos 获取 服务 实例
 * @date 2020/8/5
 */
@Slf4j
public class NacosLoadBalancerByServiceName {

    private static final String DOOR_VERSION_VALUE = "barrier_version";

    private static Logger LOGGER = LoggerFactory.getLogger(NacosLoadBalancerByServiceName.class);

    @Autowired
    private NamingService nacosNamingService;


    /**
     *
     * @param serviceName
     * @return
     */
    public List<Instance> choose(String serviceName,String version, ServerWebExchange serverWebExchange){


        List<Instance> versionInstList = new ArrayList<>();
        try {
            List<Instance> allInstances = nacosNamingService.getAllInstances(serviceName);
            if (CollectionUtils.isNotEmpty(allInstances)){
                for (Instance instance : allInstances) {
                    if (StringUtils.isNotEmpty(version)){
                        String door_version = instance.getMetadata().get(DOOR_VERSION_VALUE);
                        if (StringUtils.isNotEmpty(door_version)&&door_version.equals(version)){
                            versionInstList.add(instance);
                        }
                    }else {
                        versionInstList.add(instance);
                    }
                }
                return versionInstList;
            }else {
                LOGGER.error("[NacosLoadBalancerByServiceName fail],not serviceName available  instance");
                throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_NOT_DOING_SERVER_FAIL);
            }
        } catch (NacosException e) {
            LOGGER.error("[NacosLoadBalancerByServiceName fail],serviceName:{}",serviceName);
        }
          return null;
    }

}
